package org.djustice.apkgot;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

/**
 * @author djustice
 *
 */
public class PackageListActivity extends ListActivity {

    ProgressDialog mProgressDialog;

    String mApkList;
    String mApkUrlList;
    String mApkIconList;

    GetPageDataTask mGetPageTask;


    @Override
    public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setTitle("apkGot - apktop");
	//auntdessie001

	mApkList = "";
	mApkUrlList = "";
	mApkIconList = "";

	getPageNumber(1);
	
	mProgressDialog = ProgressDialog.show(this, "", "Loading..");
    }

    private Handler handler = new Handler() {
	@Override
	public void handleMessage(Message msg) {
	    if (msg.arg1 == 1) {
		mProgressDialog.dismiss();
		finish();
	    } else {
		mProgressDialog.dismiss();
	    }
	}
    };

    private class GetPageDataTask extends AsyncTask<String, Void, String> {
	String response;

	String inputLine;
	String subStr_a;
	String subStr_b;
	String subStr_c;

	URL url;
	URLConnection urlConnection;

	BufferedReader bufferedReader;
	
	@Override
	protected String doInBackground(String... urls) {
	    for (String u : urls) {
		try {
		    System.out.println("doInBackground(): " + u);
		    
		    url = new URL(u);
		    urlConnection = url.openConnection();
		    bufferedReader = new BufferedReader(
			    new InputStreamReader(urlConnection.getInputStream()));

		    inputLine = "";

		    while ((inputLine = bufferedReader.readLine()) != null) {
			response = response + "\n" + inputLine;
			if (inputLine.contains("<h2>") && inputLine.contains(".html")) {
			    subStr_a = inputLine.substring(19);
			    subStr_b = subStr_a.substring(0, subStr_a.indexOf("\" rel"));

			    mApkUrlList = mApkUrlList + subStr_b +  "\n";
			}

			if (inputLine.contains("<img width=\"96\"")) {
			    subStr_c = inputLine.substring(inputLine.indexOf("<img width=\"96\"") + 33, inputLine.indexOf("\" class="));
			    System.out.println("icon found: " + subStr_c);
			    downloadFile(subStr_c);
			}
		    }

		    bufferedReader.close();

		} catch (Exception e) {

		}
	    }

	    return response;
	}
    }

    /**
     * @param number
     */
    public void getPageNumber(int number) {
	mGetPageTask = new GetPageDataTask();
	String result = mGetPageTask.doInBackground(new String[] { "http://www.apktop.com/page/" + number });
	
	String a = parsePageItems(result);
	System.out.println(a);

	PackageListAdapter adapter = new PackageListAdapter(PackageListActivity.this);

	for (String item : a.split("\n")) {
	    if (!item.equals("")) {
		PackageListActivity.this.mApkList = PackageListActivity.this.mApkList + item + "\n";

		Bitmap b = BitmapFactory.decodeFile("/sdcard/download/apkGot/.icons/" + PackageListActivity.this.mApkUrlList.split("\n").length + ".png");
		BitmapDrawable d = new BitmapDrawable(b);
		adapter.addItem(new PackageItem(item, d));
	    }
	}

	PackageListActivity.this.setListAdapter(adapter);
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
	super.onListItemClick(l, v, position, id);

	Object o = getListView().getItemAtPosition(position);

	Toast.makeText(this, "You selected: " + o.toString(), Toast.LENGTH_LONG).show();
    }

    /**
     * @param page
     * @return newline separated list of individual apk page urls
     */
    public String parsePageItems(String page) {
	    System.out.println("parsePageItems(): " + page);
	String ret = "";
	for (String a : page.split("\n")) {
	    if (a.contains("<li><a href=") && a.contains("title=")) {
		String sub = a.split("title=")[1].split("\">")[0];
		if (sub.contains("</a>") == false) {
		    ret = ret + "\n" + sub.substring(1);
		}
	    }
	}

	return ret;
    }


    /**
     * @param path
     */
    public void downloadFile(String path) {
	try {
	    System.out.println("downloadFile(): " + path);
	    String state = Environment.getExternalStorageState();

	    if (Environment.MEDIA_MOUNTED.equals(state)) {
		File fPath = Environment.getExternalStoragePublicDirectory(
			     Environment.DIRECTORY_DOWNLOADS);
		File aPath = new File(fPath, "/apkGot");
		aPath.mkdir();
		File iPath = new File(fPath,"/apkGot/.icons");
		iPath.mkdir();
		File xPath;

		String outputFile = "";
		if (path.endsWith(".png")) {
		    outputFile = iPath.getPath() + "/" + mApkUrlList.split("\n").length + ".png";
		    xPath = iPath;
		} else {
		    outputFile = path.split(":::")[1];
		    xPath = new File(fPath, "/apkGot");
		}
		
		System.out.println("out: " + outputFile);

		File file = new File(xPath, outputFile);

		BufferedInputStream in = new BufferedInputStream(new URL(path.split(":::")[0]).openStream());
		FileOutputStream fos = new FileOutputStream(file);
		BufferedOutputStream out = new BufferedOutputStream(fos,1024);

		int x=0;
		byte data[] = new byte[1024];

		while((x=in.read(data,0,1024))>=0) {
		    out.write(data,0,x);
		}

		out.close();
		in.close();
	    }
	} catch (Exception e) {
	    System.out.println("\n!! failed to download, " + path);
	}
    }
}
